<template>
  <j-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    destroyOnClose
    style="top:10px"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form" hideRequiredMark>
        <a-tabs v-model="defaultActiveKey">
          <a-tab-pane tab="基本信息" key="1">
            <a-row style="width: 100%;">
              <a-col :span="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="单据编号">
                  <a-input placeholder="请输入编号" v-decorator="['documentNo', {rules: [{ required: true, message: '名称不允许为空!' }] }]" :readOnly="true"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="经办人">
                  <a-input placeholder="请输入经办人" v-decorator="['handlerId', {rules: [{ required: true, message: '名称不允许为空!' }] }]" :readOnly="true"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="申请日期">
                  <a-date-picker showTime format="YYYY-MM-DD HH:mm:ss" v-decorator="[ 'currentDate', {rules: [{ required: true, message: '请选择申请日期'}]}]" style="width: 100%" :disabled="disabled"/>
                </a-form-item></a-col>
            </a-row>
            <a-row style="width: 100%;">
              <a-col :span="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="申请人">
                  <j-dict-select-tag
                    v-decorator="['type', {}]"
                    title="申请人"
                    dictCode="mettingType"
                    placeholder="请选择申请人"
                    :triggerChange="true"
                    :disabled="disabled"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="申请单位">
                  <j-dict-select-tag
                    v-decorator="['type', {}]"
                    title="类型"
                    dictCode="mettingType"
                    placeholder="请选择申请单位"
                    :triggerChange="true"
                    :disabled="disabled"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="用车类型">
                  <j-dict-select-tag
                    v-decorator="['type', {}]"
                    title="类型"
                    dictCode="mettingType"
                    placeholder="请选择用车类型"
                    :triggerChange="true"
                    :disabled="disabled"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row style="width: 100%;">
              <a-col :span="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="申请车辆">
                  <a-input placeholder="请输入申请车辆" v-decorator="['concatMode', validatorRules.phone]" :readOnly="disabled"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="关联项目">
                  <j-dict-select-tag
                    v-decorator="['type', {}]"
                    title="类型"
                    dictCode="mettingType"
                    placeholder="请选择关联项目"
                    :triggerChange="true"
                    :disabled="disabled"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="管理员">
                  <a-input placeholder="请输入管理员" v-decorator="['concatMode', validatorRules.phone]" :readOnly="disabled"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row style="width: 100%;">
              <a-col :span="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="业务团队">
                  <j-dict-select-tag
                    v-decorator="['remindMode', {}]"
                    title="业务团队"
                    dictCode="remindMode"
                    placeholder="请选择"
                    :triggerChange="true"
                    :disabled="disabled"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="关联项目">
                  <j-dict-select-tag
                    v-decorator="['remind', {}]"
                    title="关联项目"
                    dictCode="remindTime"
                    placeholder="请选择"
                    :triggerChange="true"
                    :disabled="disabled"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :labelCol="{
                    xs: { span: 24 },
                    sm: { span: 7 }
                  }"
                  :wrapperCol="wrapperCol"
                  label="是否需要驾驶员">
                  <a-radio-group name="radioGroup" :default-value="1">
                    <a-radio :value="1">
                      是
                    </a-radio>
                    <a-radio :value="0">
                      否
                    </a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row style="width: 100%;">
              <a-col :span="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="用车日期">
                  <a-date-picker showTime format="YYYY-MM-DD HH:mm:ss" v-decorator="[ 'beginTime', {rules: [{ required: true, message: '请选择开始时间' }]}]" style="width: 100%" :disabled="disabled"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :labelCol="{
                    xs: { span: 24 },
                    sm: { span: 6 }
                  }"
                  :wrapperCol="wrapperCol"
                  label="预计归还日期">
                  <a-date-picker showTime format="YYYY-MM-DD HH:mm:ss" v-decorator="[ 'endTime', {rules: [{ required: true, message: '请选择结束时间'}]}]" style="width: 100%" :disabled="disabled"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="驾驶员">
                  <a-input placeholder="请输入管理员" v-decorator="['concatMode', validatorRules.phone]" :readOnly="disabled"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row style="width: 100%;">
              <a-col :span="8">
                <a-form-item
                  :labelCol="{
                    xs: { span: 24 },
                    sm: { span: 6 }
                  }"
                  :wrapperCol="wrapperCol"
                  label="是否已还车">
                  <a-radio-group name="radioGroup" :default-value="1">
                    <a-radio :value="1">
                      是
                    </a-radio>
                    <a-radio :value="0">
                      否
                    </a-radio>
                  </a-radio-group>
                  <!-- <div>
                    <j-select-metting-room v-decorator="['location', {rules: [{ required: !customRequired, message: '会议地点不允许为空!',trigger: 'change' }] }]" :multi="false" @change="mettingRoomChange" :disabled="disabled"></j-select-metting-room>
                  </div> -->
                </a-form-item>
              </a-col>
              <a-col :span="8" v-if="!disabled">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="还车日期"
                >
                  <a-date-picker showTime format="YYYY-MM-DD HH:mm:ss" v-decorator="[ 'beginTime', {rules: [{ required: true, message: '请选择日期' }]}]" style="width: 100%" :disabled="disabled"/>
                </a-form-item>
              </a-col>
              <a-col :span="8"></a-col>
            </a-row>
            <a-row style="width: 100%;">
              <a-col :span="24">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="事由">
                  <a-textarea placeholder="请输入事由" v-decorator="['remark', {}]" :readOnly="disabled"/>
                  <!-- <a-input placeholder="请输入自定义会议地点" v-decorator="['customLocation', {rules: [{ required: customRequired, message: '自定义会议地点不允许为空!',trigger: 'change' }] }]" :readOnly="disabled" @input="customRoomChange"/> -->
                </a-form-item>
              </a-col>
            </a-row>
            <a-row style="width: 100%;">
              <a-col :span="24">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="备注">
                  <a-textarea placeholder="请输入备注" v-decorator="['remark', {}]" :readOnly="disabled"/>
                  <!-- <a-input placeholder="请输入参与人员" v-decorator="['joinPerson', {}]" hidden/>
                  <j-select-user-by-dep v-decorator="['joinPerson', {}]" :multi="true" :disabled="disabled"></j-select-user-by-dep> -->
                </a-form-item>
              </a-col>
            </a-row>
            <a-row style="width: 100%;">
              <a-col :span="12">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="附件信息">
                  <j-upload v-model="fileList"></j-upload>
                </a-form-item>
              </a-col>
            </a-row>

          </a-tab-pane>
        </a-tabs>
      </a-form>
    </a-spin>
    <template slot="footer">
      <a-button @click="handleCancel" style="margin-right: 5px">关闭</a-button>
      <a-button type="primary" @click="previewSign" v-if="defaultActiveKey=='2'&&!disabled" style="margin-right: 5px">签到预览</a-button>
      <a-button type="primary" @click="handleOk">确认</a-button>
    </template>
    <eoa-metting-room-use-modal ref="roomUseForm" v-if="!disabled"></eoa-metting-room-use-modal>
  </j-modal>
</template>

<script>
import { getAction, getFileAccessHttpUrl, httpAction } from '@/api/manage'
import pick from 'lodash.pick'
import moment from 'moment'
import store from '@/store/'
import JDictSelectTag from '@/components/dict/JDictSelectTag.vue'
import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDep'
import JUpload from '@/components/jeecg/JUpload'
import JImageUpload from '@/components/jeecg/JImageUpload.vue'
import { VueColorpicker } from 'vue-pop-colorpicker'

export default {
  name: 'EoaMettingModal',
  components: {
    JDictSelectTag,
    JSelectUserByDep,
    JUpload,
    JImageUpload,
    'color-picker': VueColorpicker
  },
  data() {
    return {
      title: '操作',
        visible: false,
        showAvatar: false,
        showDepart: false,
        showSign: false,
        disabled: false,
        approvalDisabled: false,
        name: '',
        customRequired: false,
        defaultActiveKey: '1',
        bgColor: '#006699',
        fontColor: '#FFFFFF',
        fileList: [],
        imgList: [],
        summaryFile: [],
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules: {
          phone: { rules: [{ validator: this.validatePhone, trigger: 'blur' }] }
        },
        url: {
          add: '/api/erp/erpcarusing/erpCarUsing/add',
          edit: '/api/erp/erpcarusing/erpCarUsing/edit',
          queryById: '/api/erp/erpcarusing/erpCarUsing/queryById'
        }
      }
    },
    created () {
      this.username = store.getters.userInfo.username;
    },
    methods: {
      initDictConfig() {
        console.log('--初始化字典!')
      },
      previewSign() {
        let size = this.form.getFieldValue('fontSize');
        let routeUrl = this.$router.resolve({
          path: '/metting/eoaMettingPreview',
          query: {
            bgColor: this.bgColor,
            fontColor: this.fontColor,
            fontSize: size,
            id: this.model.id,
            userid: store.getters.userInfo.id
          }
        });
        window.open(routeUrl.href, '_blank');
      },
      eventAdd(info) {
        console.log('info', info)
        if (info && info.start && info.end) {
            this.edit({ beginTime: info.start, endTime: info.end });
        } else {
          this.edit({});
        }
      },
      eventEdit(info) {
        console.log('获取编辑页的数据', info)
        if (info && info.event && info.event.id) {
          getAction(this.url.queryById, { id: info.event.id }).then((res) => {
            if (res.success) {
            this.edit(res.result);
            }
          })
        }
      },
      getFileDownloadUrl: function (path) {
        return getFileAccessHttpUrl(path)
      },
      add () {
        console.log('12312323')
        this.edit({});
      },
      detail(record) {
        this.disabled = true;
        this.edit(record);
      },

      // 请求的编辑数据
      edit (record) {
        this.model = {};
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'documentNo', 'currentDate', 'handlerId', 'affiliatedName', 'affiliatedUnit', 'concatMode', 'location', 'customLocation', 'content', 'status', 'intervalDay', 'repeatStrategy', 'remindMode', 'joinPerson', 'otherPerson', 'approvalStatus', 'files', 'remark', 'bgColor', 'bgImg', 'fontColor', 'fontSize', 'showAvatar', 'showDepart', 'showSign', 'bpmStatus', 'summaryUploader'))
          this.form.setFieldsValue({ originator: record.originator ? record.originator : store.getters.userInfo.username });
          this.form.setFieldsValue({ contacts: record.contacts ? record.contacts : store.getters.userInfo.username });
          // 时间格式化
          this.form.setFieldsValue({ beginTime: this.model.beginTime ? moment(this.model.beginTime) : null })
          this.form.setFieldsValue({ endTime: this.model.endTime ? moment(this.model.endTime) : null })
        });
        if (this.model.id) {
          console.log('record::::>', record)
          let timer = setTimeout(() => {
            this.fileList = record.files;
            this.imgList = record.bgImg;
            this.summaryFile = record.summaryFile;
            this.showAvatar = record.showAvatar == '1';
            this.showDepart = record.showDepart == '1';
            this.showSign = record.showSign == '1';
            this.customRequired = !!((record.customLocation && record.customLocation.length > 0));
            this.bgColor = record.bgColor;
            this.fontColor = record.fontColor;
            clearTimeout(timer)
          }, 5)
        }
        var currentdate = this.getDateTime()
        console.log(currentdate)
        this.form.setFieldsValue({ currentDate: moment(currentdate) })
      },
      close () {
        this.initalDate()
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if (!this.model.id) {
              httpurl += this.url.add;
              method = 'post';
            } else {
              httpurl += this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            // 时间格式化
            formData.beginTime = formData.beginTime ? formData.beginTime.format('YYYY-MM-DD HH:mm:ss') : null;
            formData.endTime = formData.endTime ? formData.endTime.format('YYYY-MM-DD HH:mm:ss') : null;
            if (that.fileList && that.fileList.length > 0 && !that.disabled) {
              formData.files = that.fileList
            }
            if (that.imgList && that.imgList.length > 0 && !that.disabled) {
              formData.bgImg = that.imgList
            }
            if (that.summaryFile && that.summaryFile.length > 0) {
              formData.summaryFile = that.summaryFile
            }
            if (that.fontColor && !that.disabled) {
              formData.fontColor = that.fontColor
            }
            if (that.bgColor && !that.disabled) {
              formData.bgColor = that.bgColor
            }
            console.log('formData==>', formData)
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit('ok');
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
        })
      },
      handleCancel () {
        this.close()
      },
      initalDate() {
        this.defaultActiveKey = '1';
        this.fileList = [];
        this.imgList = [];
        this.showAvatar = false;
        this.showDepart = false;
        this.showSign = false;
        this.bgColor = '#006699';
        this.fontColor = '#FFFFFF';
      },
      mettingRoomChange(room, processStatus) {
          this.form.setFieldsValue(pick({ 'location': room }, 'location'));
          this.form.setFieldsValue(pick({ 'approvalStatus': processStatus }, 'approvalStatus'));
          if (processStatus == '1') {
            this.approvalDisabled = true;
          } else {
            this.approvalDisabled = false;
          }
        this.customRequired = false
        this.$nextTick(() => {
          this.form.validateFields(['location'], { force: true });
          this.form.validateFields(['customLocation'], { force: true });
        });
      },
      customRoomChange(value) {
        let fieldValue = this.form.getFieldValue('location')
        if (!fieldValue) {
          this.customRequired = true
          this.approvalDisabled = false;
          this.$nextTick(() => {
            this.form.validateFields(['location'], { force: true });
            this.form.validateFields(['customLocation'], { force: true });
          });
        }
      },
      showUse() {
          this.$refs.roomUseForm.show()
      },
      avatarChange(checked) {
        this.showAvatar = checked;
        if (this.showAvatar) {
          this.form.setFieldsValue(pick({ 'showAvatar': '1' }, 'showAvatar'));
        } else {
          this.form.setFieldsValue(pick({ 'showAvatar': '0' }, 'showAvatar'));
        }
      },
      departChange(checked) {
        this.showDepart = checked;
        if (this.showDepart) {
          this.form.setFieldsValue(pick({ 'showDepart': '1' }, 'showDepart'));
        } else {
          this.form.setFieldsValue(pick({ 'showDepart': '0' }, 'showDepart'));
        }
      },
      signChange(checked) {
        this.showSign = checked;
        if (this.showSign) {
          this.form.setFieldsValue(pick({ 'showSign': '1' }, 'showSign'));
        } else {
          this.form.setFieldsValue(pick({ 'showSign': '0' }, 'showSign'));
        }
      },
      validatePhone(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if (new RegExp(/^1[3|4|5|7|8|9][0-9]\d{8}$/).test(value)) {
            callback()
          } else {
            callback('请输入正确格式的手机号码!');
          }
        }
      },
     bgColorChange (color) {
       this.bgColor = this.rgbToHexadecimal(color);
      },
      fontColorChange(color) {
        this.fontColor = this.rgbToHexadecimal(color);
      },
     rgbToHexadecimal(color) {
       if (color.startsWith('rgb')) {
         let RGB = color.substring(4, color.length - 1).split(',')
         let hexcode = '#';
         let c = '0123456789ABCDEF'
         for (var x = 0; x < 3; x++) {
           let n = RGB[x];
           let b = ''
           let a = n % 16;
           b = c.substr(a, 1);
           a = (n - a) / 16;
           hexcode += c.substr(a, 1) + b
         }
        return hexcode;
       } else {
         return '#ffffff';
       }
     },

      //  获取当前日期时间

      getDateTime () {
        var date = new Date();
        var hengGang = '-';
        var maoHao = ':';
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var curDate = date.getDate();
        var curHours = date.getHours();
        var curMinutes = date.getMinutes();
        var curSeconds = date.getSeconds();

        if (month >= 1 && month <= 9) {
          month = '0' + month;
        }
        if (curDate >= 0 && curDate <= 9) {
          curDate = '0' + curDate;
        }
        if (curHours >= 0 && curHours <= 9) {
          curHours = '0' + curHours;
        }
        if (curMinutes >= 0 && curMinutes <= 9) {
          curMinutes = '0' + curMinutes;
        }
        if (curSeconds >= 0 && curSeconds <= 9) {
          curSeconds = '0' + curSeconds;
        }
        var currentdate = '';
        currentdate = year + hengGang + month + hengGang + curDate
          return currentdate;
        // if (type == 'year') {
        //   currentdate = year;
        //   return currentdate;
        // } else if (type == 'month') {
        //   currentdate = year + hengGang + month;
        //   return currentdate;
        // } else {
        //   currentdate = year + hengGang + month + hengGang + curDate + ' ' + curHours + maoHao + curMinutes + maoHao + curSeconds;
        //   return currentdate;
        // }
      }
    }
  }
</script>

<style lang="less" scoped>
  .vue-colorpicker{
    border: 0 !important;
  }
  .colorSpan{
    display: flex;
    align-items: center;
    justify-content: center;
    border:1px solid #d9d9d9;
    border-radius: 5px;
    width: 100px;
   }
</style>
